import { reactive, ref } from 'vue'
import { format } from 'date-fns'
import { TaskInstance } from '@/service/modules/task-instances/types'
import {
  queryTaskInstancesReq,
  stopTmpTaskReq
} from '@/service/modules/task-instances'

export function useTable() {
  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    taskDefinedId: 0,
    searchParam: {
      username: '',
      startEndTime: ref()
    },
    list: [],
    loading: false,
    currentRecord: {} as TaskInstance,
    showViewLogModal: false,
    showViewQueryResultModal: false,
    row: {}
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true
    let startTime = ''
    let endTime = ''
    if (state.searchParam.startEndTime) {
      startTime = format(
        new Date(state.searchParam.startEndTime[0]),
        'yyyy-MM-dd HH:mm:ss'
      )
      endTime = format(
        new Date(state.searchParam.startEndTime[1]),
        'yyyy-MM-dd HH:mm:ss'
      )
    }
    const res = await queryTaskInstancesReq({
      page: state.page,
      limit: state.limit,
      username: state.searchParam.username,
      startTime: startTime,
      endTime: endTime,
      taskDefinedId: state.taskDefinedId,
      isTmp: true
    })
    state.loading = false
    if (res.resp_code === 0) {
      state.list = res.data
      state.count = res.count
    }
  }

  const updateList = () => {
    if (state.list.length === 1 && state.page > 1) {
      --state.page
    }
    getList()
  }

  const stopTask = (processInstanceId: number) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('taskManage.stopTaskTips'),
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await stopTmpTaskReq({
          executeType: 'STOP',
          processInstanceId: processInstanceId
        })
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }
  const onOperationClick = (
    data: { rowData: TaskInstance },
    type: 'stopTask' | 'viewLog' | 'viewQueryResult'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'stopTask':
        stopTask(data.rowData.processInstanceId)
        break
      case 'viewLog':
        state.showViewLogModal = true
        break
      case 'viewQueryResult':
        state.showViewQueryResultModal = true
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getList()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getList()
  }

  return {
    state,
    changePage,
    changePageSize,
    updateList,
    onOperationClick
  }
}
